package o2o.web.actions.user;

//用户管理相关

import com.google.gson.Gson;
import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import map.HttpRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import o2o.cache.user.UserInfoExtraMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.user.UserPwdMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.config.memcached.MemcacheUtil;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.device.door.DeviceCompanyContact;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.sys.SysCityAdmin;
import o2o.dao.PO.user.USER_COMPANY_STATE;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.user.UserInfoExtra;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.user.UserInfoVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.utils.CommonUtils;
import o2o.web.actions.company.SysCityCompanyMan;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class UserManagerAction {

    //获取所有用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/list")
    @ResponseBody
    public String admin_user_list(String token, Integer userType, String username, String content, Long startTime, Long endTime, String city, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(userType)) {
            userType = 0;
        }
        List<UserInfoVO> list = null;
        // 用户
        if (user.getUserType() == UserType.SUPER_ADMIN || user.getUserType() == UserType.SUPER_COMPANY) {
            // 超级管理
            list = getUserList(userType, false, startTime, endTime);  // 获取所有用户
        }

        if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
            if (ValidateUtil.isNotNull(city)) {
                city = JYPinyinHelper.isChinese(city) ? JYPinyinHelper.toHanyuPinyin(city) : city.toLowerCase();
            }
        }

        if (ValidateUtil.isAbsList(list)) {
            boolean needCheck = false;
            if (ValidateUtil.isNotNull(username) || ValidateUtil.isNotNull(content) || ValidateUtil.isNotNull(city)) {
                needCheck = true;
            }
            List<UserInfoVO> tmpList = new ArrayList<UserInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                UserInfoVO userInfoVO = list.get(i);
                if (null == userInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNull(userInfoVO.getUsername())) {
                    continue;
                }
                if ("admin".equalsIgnoreCase(userInfoVO.getUsername()) || "sadmin".equalsIgnoreCase(userInfoVO.getUsername())) {
                    continue;
                }
                if (userInfoVO.getUsername().length() >= 20) {
                    continue;
                }
                if (needCheck) {
                    //账号
                    if (ValidateUtil.isNotNull(username)) {
                        if ((ValidateUtil.isNotNull(userInfoVO.getUsername()) && userInfoVO.getUsername().contains(username)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getTelPhone()) && userInfoVO.getTelPhone().contains(username)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getPhone2()) && userInfoVO.getPhone2().contains(username)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getPhone()) && userInfoVO.getPhone().contains(username))) {
                            // 包含就可以
                        } else {
                            continue;
                        }
                    }
                    //内容
                    if (ValidateUtil.isNotNull(content)) {
                        if ((userInfoVO.getUsername().contains(content) ||
                                (ValidateUtil.isNotNull(userInfoVO.getName()) && userInfoVO.getName().contains(content)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getCity()) && userInfoVO.getCity().contains(content)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getTelPhone()) && userInfoVO.getTelPhone().contains(content)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getPhone()) && userInfoVO.getPhone().contains(content)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getPhone2()) && userInfoVO.getPhone2().contains(content)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getAddress()) && userInfoVO.getAddress().contains(content))
                        )) {

                        } else {
                            continue;
                        }
                    }

                    //城市
                    if (ValidateUtil.isNotNull(city)) {
                        if ((ValidateUtil.isNotNull(userInfoVO.getCity()) && userInfoVO.getCity().contains(city)) ||
                                (ValidateUtil.isNotNull(userInfoVO.getAddress()) && userInfoVO.getAddress().contains(city))) {


                        } else {
                            continue;
                        }
                    }
                }
                UserInfoExtra extra = UserInfoExtraMemory.getInstance().getByUsername(list.get(i).getUsername());
                if (extra != null && ValidateUtil.isAbsLong(extra.getLastOnlineTime())) {
                    list.get(i).setLastOnlineTime(extra.getLastOnlineTime());
                }
                tmpList.add(list.get(i));
            }
            JYListSort.sortDesc(tmpList, "createTime");

            //分页返回
            JYPageUtils.PageList pageList = JYPageUtils.getList(tmpList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                List<UserInfoVO> voList = new ArrayList<UserInfoVO>();
                for (int i = 0; i < pageList.list.size(); i++) {
                    if (null == pageList.list.get(i)) {
                        continue;
                    }
                    voList.add((UserInfoVO) pageList.list.get(i));
                }

                if (ValidateUtil.isAbsList(voList)) {
                    try {
                        mergeUserInformation(voList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    DateUtils.StartEndOfDayTimestamp se = DateUtils.getStartEndTimestamp(DateUtils.getCurrTime());
                    long count = 0;
                    if (null != se) {
                        Long startT = se.startTimestamp;
                        Long endT = se.endTimestamp;
                        //当日用户量
                        count = getTodayUserCount(voList, startT, endT);
                    }
                    JSONObject obj = new JSONObject();
                    obj.put("status", 1);
                    obj.put("todayUserCount", count);
                    obj.put("totalCount", pageList.totalCount);
                    obj.put("data", com.alibaba.fastjson.JSONArray.toJSON(voList));
                    obj.put("size", voList.size());
                    return obj.toString();
//                    return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
                }
            }

        }

        return AjaxResult.successResult(0, 0, null);
    }


    // 将用户信息和下单信息整合
    public static void mergeUserInformation(List<UserInfoVO> list) {
        Set<String> usernameSet = list.stream().map(a -> a.getUsername()).collect(Collectors.toSet());
        Map<String, Map<String, Object>> map = listOfCountUserConsumption(usernameSet);
        if (map != null) {
            for (UserInfoVO vo : list) {
                Map<String, Object> temp = map.get(vo.getUsername());
                if (temp != null) {
                    vo.setFinishOrderCount(Integer.parseInt(temp.get("counts").toString())).setFinishOrderTotalMoney(Double.parseDouble(temp.get("totalMoney").toString()));
                } else {
                    vo.setFinishOrderCount(0).setFinishOrderTotalMoney(0.0d);
                }
            }
        }
    }

    //  获取用户的消费情况
    public static Map<String, Map<String, Object>> listOfCountUserConsumption(Set<String> usernameSet) {
        if (usernameSet == null || usernameSet.isEmpty()) {
            return null;
        }
//        SELECT username,COUNT(*),SUM(IFNULL(totalPrice,0)) FROM order_info WHERE delFlag = 0  AND isRefundApply !=2 AND isPartCancelApply!=2 AND orderstatus IN (9,19,64) AND username IN ('15269020596')  GROUP BY username ;
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT username as username,COUNT(*) as counts,SUM(IFNULL(totalPrice,0)) as totalMoney ")
                .append(" FROM order_info WHERE delFlag = 0  AND isRefundApply !=2 AND isPartCancelApply!=2 ")
                .append(" AND orderstatus IN (").append(StringUtils.join(ORDER_STATUS.finishDeliverSet, ",")).append(") ")
                .append(" and username IN (").append(StringUtils.join(usernameSet, ",")).append(") ")
                .append(" group by username");
        List<HashMap<String, Object>> mapList = null;
        try {
            mapList = UserDaoSql.getInstance().queryBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mapList != null && mapList.size() > 0) {
            Map<String, Map<String, Object>> map = new HashMap<>();
            for (Map<String, Object> temp : mapList) {
                Map<String, Object> t = new HashMap<>();
                String username = temp.get("username").toString();
                Object counts = temp.get("counts");
                Object totalMoney = temp.get("totalMoney");
                t.put("counts", counts == null ? 0 : Integer.parseInt(counts.toString()));
                t.put("totalMoney", totalMoney == null ? 0 : Double.parseDouble(totalMoney.toString()));
                map.put(username, t);
            }
            return map;
        }
        return null;
    }


    //获取所有店家
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shoper/list")
    @ResponseBody
    public String admin_shoper_list(String token) {

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        List<UserInfoVO> list = getUserList(UserType.SHOP_OWNER, false);
        return AjaxResult.successResult(list.size(), list.size(), list);
    }

    //获取所有管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/admin/list")
    @ResponseBody
    public String admin_admin_list(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }


        List<UserInfoVO> list = getUserList(UserType.ADMIN, false);
        return AjaxResult.successResult(list.size(), list.size(), list);
    }


    //----------------------配送员管理
    //获取所有配送员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/delivery/list")
    @ResponseBody
    public String admin_delivery_list(String token) {

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        List<UserInfoVO> list = getUserList(UserType.POSTMAN, false);
        return AjaxResult.successResult(list.size(), list.size(), list);
    }


    //---------------------用户管理
    //锁定用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/lock")
    @ResponseBody
    public String admin_user_lock(String token, String usernames) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNull(usernames)) {
            return AjaxResult.errorResult("请选择要锁定的用户");
        }


//        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
//        if (null != userInfo) {
//            return AjaxResult.errorResult("该用户不存在");
//        }

        //解锁用户
        ResultInfo resultInfo = lockUser(user.getUsername(), usernames, 1);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //获取已锁定用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/lock/list")
    @ResponseBody
    public String admin_user_lock_list(String token, String username, String city,
                                       @RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        List<UserInfoVO> list = null;
        if (user.getUserType() == UserType.SUPER_ADMIN || user.getUserType() == UserType.SUPER_COMPANY) {
            // 超级管理
            list = getUserList(0, true);
        }

        // 获取所有锁定的用户
//        if (ValidateUtil.isAbsList(list)) {//分页
//            totalCount = list.size();
//            if (ValidateUtil.isAbsInteger(page) && ValidateUtil.isAbsInteger(size)) {
//                if (list.size() > page * size) {
//                    int i = (int) ((page - 1) * size);
//                    LinkedList<UserInfoVO> listf = new LinkedList<UserInfoVO>();
//                    for (int j = 1; j <= size; j++) {
//                        listf.add(list.get(i + j));
//                    }
//                    return AjaxResult.successResult(totalCount, size, listf);
//                } else if (list.size() < page * size && list.size() > (page - 1) * size) {
//                    LinkedList<UserInfoVO> listf = new LinkedList<UserInfoVO>();
//                    for (int j = (int) ((page - 1) * size); j < list.size(); j++) {
//                        listf.add(list.get(j));
//                    }
//                    return AjaxResult.successResult(totalCount, listf.size(), listf);
//                }
//            } else {
//                List<UserInfoVO> voList = new ArrayList<UserInfoVO>();
//
//                if (list.size() < 10) {
//                    size = list.size();
//                } else {
//                    size = 10;
//                }
//                for (int i = 0; i < size; i++) {
//                    voList.add(list.get(i));
//                }
//                return AjaxResult.successResult(totalCount, voList.size(), voList);
//            }
//        }

        if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
            if (ValidateUtil.isNotNull(city)) {
                city = JYPinyinHelper.isChinese(city) ? JYPinyinHelper.toHanyuPinyin(city) : city.toLowerCase();
            }
        }

        if (ValidateUtil.isAbsList(list)) {
            List<UserInfoVO> tmpList = new ArrayList<UserInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                UserInfoVO userInfoVO = list.get(i);
                if (null == userInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNull(userInfoVO.getUsername())) {
                    continue;
                }
                //账号
                if (ValidateUtil.isNotNull(username)) {
                    if ((ValidateUtil.isNotNull(userInfoVO.getUsername()) && userInfoVO.getUsername().contains(username)) ||
                            (ValidateUtil.isNotNull(userInfoVO.getTelPhone()) && userInfoVO.getTelPhone().contains(username)) ||
                            (ValidateUtil.isNotNull(userInfoVO.getPhone2()) && userInfoVO.getPhone2().contains(username)) ||
                            (ValidateUtil.isNotNull(userInfoVO.getPhone()) && userInfoVO.getPhone().contains(username))) {
                        // 包含就可以
                    } else {
                        continue;
                    }
                }
                //城市
                if (ValidateUtil.isNotNull(city)) {
                    if ((ValidateUtil.isNotNull(userInfoVO.getCity()) && userInfoVO.getCity().contains(city)) ||
                            (ValidateUtil.isNotNull(userInfoVO.getAddress()) && userInfoVO.getAddress().contains(city))) {
                    } else {
                        continue;
                    }
                }
                tmpList.add(userInfoVO);
            }
            JYListSort.sortDesc(tmpList, "createTime");
            //分页返回
            JYPageUtils.PageList pageList = JYPageUtils.getList(tmpList, page, size);
            return AjaxResult.successResult(pageList.list, pageList.totalCount);
        }
        return AjaxResult.successResult(null, 0);
    }

    //解锁用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/unlock")
    @ResponseBody
    public String admin_user_unlock(String token, String usernames) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNull(usernames)) {
            return AjaxResult.errorResult("请选择要锁定的用户");
        }


//        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
//        if (null != userInfo) {
//            return AjaxResult.errorResult("该用户不存在");
//        }

        //解锁用户
        ResultInfo resultInfo = lockUser(user.getUsername(), usernames, 0);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }


    //删除用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/del")
    @ResponseBody
    public String admin_user_del(String token, String usernames) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有删除用户的权限");
        }

        if (ValidateUtil.isNull(usernames)) {
            return AjaxResult.errorResult("请选择要删除的用户");
        }


//        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
//        if (null != userInfo) {
//            return AjaxResult.errorResult("该用户不存在");
//        }

        String usStr = usernames.replaceAll(",", "','");
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.UserInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username in ('").append(usStr).append("') and delFlag = 0");

        StringBuilder sbStr = new StringBuilder();
        sbStr.append("update ").append(PojoTables.UserPasswordInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username in ('").append(usStr).append("') and delFlag = 0");
        System.out.println(sbStr.toString());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().executeBySql(sbStr.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除用户失败，请稍后再试");
        }
        UserInfoMemory.getInstance().del(usernames);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_DEL).setStr01(usernames);//o2o.business.jms  MQDataBusiness
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 删除用户的密码
        String temp[] = usernames.split(",");
        if (temp != null && temp.length > 0) {
            for (String s : temp) {
                UserPwdMemory.getInstance().delPassword(s);
            }
        }


        return AjaxResult.successResult();
    }

    // 用户下线
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/token/del")
    @ResponseBody
    public String admin_user_re(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有删除用户的权限");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要下线的用户");
        }

        MemcacheUtil.removeByUsername(username);

        return AjaxResult.successResult();
    }


    //-----------------------------------业务员
    //业务员管理
    //查询所有业务员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/business/list")
    @ResponseBody
    public String admin_business_list(String token, String city, String province, String county, Integer isLock, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }


        Expression expression = Expression.getInstance();
        if (ValidateUtil.isNotNull(city)) {
            expression.addChild("city", city);
        }
        if (ValidateUtil.isNotNull(province)) {
            expression.addChild("province", province);
        }
        if (ValidateUtil.isNotNull(county)) {
            expression.addChild("county", county);
        }
        expression.addChild("userType", UserType.BUSINESS_MAN);
        expression.addChild("delFlag", 0);

        if (null != isLock && isLock > 0) {
            if (0 == 1 - isLock) {//停用
                expression.addChild("isLock", 1);
            } else if (0 == 2 - isLock) {//未停用
                expression.addChild("isLock", 0);
            }
        }
        QueryCondition query = new QueryCondition();
        query.addCondition(expression);
        query.addOrders("createTime");
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.UserInfo, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.UserInfo, query);

        List<UserInfo> list = null;
        Long count = 0l;
        try {
            list = (List<UserInfo>) UserDaoSql.getInstance().list(UserInfo.class, sql);
            count = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(count, list.size(), list);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //新增业务员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/business/add")
    @ResponseBody
    public String admin_business_add(String token, UserInfo info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("请输入完整信息");
        }
        if (ValidateUtil.isNull(info.getUsername())) {
            return AjaxResult.errorResult("账号不能为空");
        }
        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("姓名不能为空");
        }
        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("城市不能为空");
        }

        info.setUserType(UserType.BUSINESS_MAN);
        info.setCreateUser(user.getUsername());

        Long time = DateUtils.getCurrTime();
        info.setCreateTime(time);

        ResultInfo resultInfo = User.addUser(info, "123456");
        if (null == resultInfo) {
            return AjaxResult.errorResult("添加失败，请稍后再试");
        } else if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //删除业务员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/business/delete")
    @ResponseBody
    public String admin_business_delete(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要删除的业务员");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该业务员不存在");
        }
        if (0 != UserType.BUSINESS_MAN - userInfo.getUserType()) {
            return AjaxResult.errorResult("该用户不是业务员");
        }

        if (!User.hasCityAuth(user.getUsername(), userInfo.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }


        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.UserInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username ='").append(username).append("'  and delFlag = 0");

        StringBuilder sbStr = new StringBuilder();
        sbStr.append("update ").append(PojoTables.UserPasswordInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username ='").append(username).append("' and delFlag = 0");
        System.out.println(sbStr.toString());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().executeBySql(sbStr.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除业务员失败，请稍后再试");
        }
        UserInfoMemory.getInstance().del(username);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_DEL).setStr01(username);//o2o.business.jms  MQDataBusiness
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }


    //锁定业务员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/business/lock")
    @ResponseBody
    public String admin_business_lock(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要锁定的业务员");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该业务员不存在");
        }
        if (0 != UserType.BUSINESS_MAN - userInfo.getUserType()) {
            return AjaxResult.errorResult("该用户不是业务员");
        }


        ResultInfo resultInfo = lockUser(user.getUsername(), username, 1);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //解锁业务员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/business/unlock")
    @ResponseBody
    public String admin_business_unlock(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要锁定的业务员");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该业务员不存在");
        }
        if (0 != UserType.BUSINESS_MAN - userInfo.getUserType()) {
            return AjaxResult.errorResult("该用户不是业务员");
        }


        ResultInfo resultInfo = lockUser(user.getUsername(), username, 0);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //-----------------------------------客服
    //查询所有客服
    @RequestMapping(method = RequestMethod.POST, value = "/admin/customer/service/list")
    @ResponseBody
    public String admin_service_list(String token, String city, String province, String county, String username, Integer isLock, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }


        Expression expression = Expression.getInstance();
        if (ValidateUtil.isNotNull(city)) {
            expression.addChild("city", city);
        }
        if (ValidateUtil.isNotNull(province)) {
            expression.addChild("province", province);
        }
        if (ValidateUtil.isNotNull(county)) {
            expression.addChild("county", county);
        }
        expression.addChild("userType", UserType.CUSTOMER_SERVICE);
        expression.addChild("delFlag", 0);

        if (null != isLock && isLock > 0) {
            if (0 == 1 - isLock) {//停用
                expression.addChild("isLock", 1);
            } else if (0 == 2 - isLock) {//未停用
                expression.addChild("isLock", 0);
            }
        }
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", username);
        }
        QueryCondition query = new QueryCondition();
        query.addCondition(expression);
        query.addOrders("createTime");
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.UserInfo, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.UserInfo, query);

        List<UserInfo> list = null;
        Long count = 0l;
        try {
            list = (List<UserInfo>) UserDaoSql.getInstance().list(UserInfo.class, sql);
            count = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(count, list.size(), list);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //新增客服
    @RequestMapping(method = RequestMethod.POST, value = "/admin/customer/service/add")
    @ResponseBody
    public String admin_service_add(String token, UserInfo info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("请输入完整信息");
        }
        if (ValidateUtil.isNull(info.getUsername())) {
            return AjaxResult.errorResult("账号不能为空");
        }
        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("姓名不能为空");
        }
        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("城市不能为空");
        }

        info.setUserType(UserType.CUSTOMER_SERVICE);
        info.setCreateUser(user.getUsername());

        Long time = DateUtils.getCurrTime();
        info.setCreateTime(time);

        ResultInfo resultInfo = User.addUser(info, "123456");
        if (null == resultInfo) {
            return AjaxResult.errorResult("添加失败，请稍后再试");
        } else if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //删除客服
    @RequestMapping(method = RequestMethod.POST, value = "/admin/customer/service/delete")
    @ResponseBody
    public String admin_service_delete(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要删除的客服");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该客服不存在");
        }
        if (0 != UserType.CUSTOMER_SERVICE - userInfo.getUserType()) {
            return AjaxResult.errorResult("该用户不是客服人员");
        }

        if (!User.hasCityAuth(user.getUsername(), userInfo.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }


        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.UserInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username ='").append(username).append("'  and delFlag = 0");

        StringBuilder sbStr = new StringBuilder();
        sbStr.append("update ").append(PojoTables.UserPasswordInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username ='").append(username).append("' and delFlag = 0");
        System.out.println(sbStr.toString());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().executeBySql(sbStr.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除客服失败，请稍后再试");
        }
        UserInfoMemory.getInstance().del(username);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_DEL).setStr01(username);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }


    //锁定客服
    @RequestMapping(method = RequestMethod.POST, value = "/admin/customer/service/lock")
    @ResponseBody
    public String admin_service_lock(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要锁定的客服");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该客服不存在");
        }
        if (0 != UserType.CUSTOMER_SERVICE - userInfo.getUserType()) {
            return AjaxResult.errorResult("该用户不是客服");
        }


        ResultInfo resultInfo = lockUser(user.getUsername(), username, 1);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //解锁客服
    @RequestMapping(method = RequestMethod.POST, value = "/admin/customer/service/unlock")
    @ResponseBody
    public String admin_service_unlock(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要锁定的客服");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该客服不存在");
        }
        if (0 != UserType.CUSTOMER_SERVICE - userInfo.getUserType()) {
            return AjaxResult.errorResult("该用户不是客服");
        }


        ResultInfo resultInfo = lockUser(user.getUsername(), username, 0);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }


    //-----------------------------------通用普通人员管理
    //查询所有
    @RequestMapping(method = RequestMethod.POST, value = "/admin/normal/user/list")
    @ResponseBody
    public String admin_financial_list(String token, String city, String province, String county,
                                       Integer userType,
                                       Integer isLock,
                                       String username,
                                       Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasCityAuth(user.getUsername(), city, user.getUserType()) && !User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == userType) {
            return AjaxResult.errorResult("请选择类型");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
            if (ValidateUtil.isNotNull(city)) {
                city = JYPinyinHelper.isChinese(city) ? JYPinyinHelper.toHanyuPinyin(city) : city.toLowerCase();
            }
        }

        Expression expression = Expression.getInstance();
        if (ValidateUtil.isNotNull(city)) {
            expression.addChild("city", city);
        }
        if (ValidateUtil.isNotNull(province)) {
            expression.addChild("province", province);
        }
        if (ValidateUtil.isNotNull(county)) {
            expression.addChild("county", county);
        }
        expression.addChild("userType", userType);
        expression.addChild("delFlag", 0);

        if (null != isLock && isLock > 0) {
            if (0 == 1 - isLock) {//停用
                expression.addChild("isLock", 1);
            } else if (0 == 2 - isLock) {//未停用
                expression.addChild("isLock", 0);
            }
        }
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", username);
        }
        QueryCondition query = new QueryCondition();
        query.addCondition(expression);
        query.addOrders("createTime");
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.UserInfo, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.UserInfo, query);

        List<UserInfo> list = null;
        Long count = 0l;
        try {
            list = (List<UserInfo>) UserDaoSql.getInstance().list(UserInfo.class, sql);
            count = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(count, list.size(), list);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    // 查询所有的分销用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user-distribute/list")
    @ResponseBody
    public String admin_financial_list(String token, String city, String province, String county,
                                       Integer userType,
                                       String username,
                                       @RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
            if (ValidateUtil.isNotNull(city)) {
                city = JYPinyinHelper.isChinese(city) ? JYPinyinHelper.toHanyuPinyin(city) : city.toLowerCase();
            }
        }

        StringBuffer sql = new StringBuffer();
        sql.append(" from ").append(PojoTables.UserInfo)
                .append(" where delFlag = 0 and (userRole & 2) > 0 ");
        if (!StringUtils.isBlank(province)) {
            sql.append(" and province = '").append(province).append("'");
        }
        if (!StringUtils.isBlank(city)) {
            sql.append(" and city = '").append(city).append("'");
        }
        if (!StringUtils.isBlank(county)) {
            sql.append(" and county = '").append(county).append("'");
        }
        if (userType != null && userType > 0) {
            sql.append(" and userType = ").append(userType);
        }
        if (!StringUtils.isBlank(username)) {
            sql.append(" and username like '%").append(username).append("%'");
        }
        String selectSql = "select * " + sql.toString() + " order by createTime limit " + (page - 1) * size + "," + size;
        String sqlCount = "select count(*) as counts " + sql.toString();
        List<UserInfo> list = null;
        Long count = 0l;
        try {
            list = (List<UserInfo>) UserDaoSql.getInstance().list(UserInfo.class, selectSql);
            count = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败");
        }
        if (ValidateUtil.isAbsList(list)) {
            List<UserInfoVO> reList = new ArrayList<>();
            for (UserInfo info : list) {
                UserInfoVO vo = new UserInfoVO();
                BeanUtils.copyProperties(info, vo);
                if (ValidateUtil.isNotNull(vo.getSignPhoto())) {
                    if (ValidateUtil.isNotNetUrl(vo.getSignPhoto())) {
                        vo.setSignature(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getSignPhoto());
                    }
                }
                reList.add(vo);
            }
            return AjaxResult.successResult(count, reList.size(), reList);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //新增
    @RequestMapping(method = RequestMethod.POST, value = "/admin/normal/user/add")
    @ResponseBody
    public String admin_financial_add(String token, UserInfo info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("请输入完整信息");
        }
        if (ValidateUtil.isNull(info.getUsername())) {
            return AjaxResult.errorResult("账号不能为空");
        }
        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("姓名不能为空");
        }
        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("城市不能为空");
        }
        info.setCreateUser(user.getUsername());
        info.setId(null);
        Long time = DateUtils.getCurrTime();
        info.setCreateTime(time);

        ResultInfo resultInfo = User.addUser(info, "123456");
        if (null == resultInfo) {
            return AjaxResult.errorResult("添加失败，请稍后再试");
        } else if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //编辑用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/normal/user/modify")
    @ResponseBody
    public String admin_financial_modify(String token, UserInfo info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("请输入完整信息");
        }

        if (ValidateUtil.isNull(info.getUsername())) {
            return AjaxResult.errorResult("请先选择用户");
        }
        UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(info.getUsername());
        if (null == userinfo) {
            return AjaxResult.errorResult("当前用户不存在，请查证");
        }

        String city = info.getCity();
        if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
            if (ValidateUtil.isNotNull(city)) {
                city = JYPinyinHelper.isChinese(city) ? JYPinyinHelper.toHanyuPinyin(city) : city.toLowerCase();
            }
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.UserInfo).append(" set name='").append(info.getName())
                .append("',telPhone='").append(info.getTelPhone()).append("',sex='").append(info.getSex())
                .append("',updateUser='").append(user.getUsername())
                .append("',province='").append(info.getProvince()).append("',city='").append(city).append("',county='").append(info.getCounty())
                .append("',address='").append(info.getAddress()).append("',rate=").append(info.getRate())
                .append(" where delFlag =0 and username = '").append(info.getUsername()).append("'");
        try {
            UserDaoSql.getInstance().executeUpdateBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }
        UserInfoMemory.getInstance().modifyUserInfo(info.getUsername());
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_MODIFY).setStr01(info.getUsername());//o2o.business.jms  MQDataBusiness
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }


    //删除
    @RequestMapping(method = RequestMethod.POST, value = "/admin/normal/user/delete")
    @ResponseBody
    public String admin_financial_delete(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要删除的客服");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该账号不存在");
        }
        if (!User.hasCityAuth(user.getUsername(), userInfo.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }


        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.UserInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username ='").append(username).append("'  and delFlag = 0");

        StringBuilder sbStr = new StringBuilder();
        sbStr.append("update ").append(PojoTables.UserPasswordInfo).append(" set delFlag = 1,updateUser = '")
                .append(user.getUsername()).append("' where username ='").append(username).append("' and delFlag = 0");
        System.out.println(sbStr.toString());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().executeBySql(sbStr.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }
        UserInfoMemory.getInstance().del(username);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_DEL).setStr01(username);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }


    //锁定或解锁
    @RequestMapping(method = RequestMethod.POST, value = "/admin/normal/user/lock")
    @ResponseBody
    public String admin_financial_lock(String token, String username, Integer isLock) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要锁定的账号");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("该账号不存在");
        }

        ResultInfo resultInfo = lockUser(user.getUsername(), username, isLock);//解锁用户  1锁定，0解锁
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //---------根据username获取所有用户信息


    // 新增公司账号
    @RequestMapping(method = RequestMethod.POST, value = "/user/company/add")
    @ResponseBody
    public String user_add(String token, String username, String city, String province, String county, String region,
                           String name, String signature, String telPhone, String phone2, String sex, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }


        if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
            if (ValidateUtil.isNotNull(city)) {
                city = JYPinyinHelper.isChinese(city) ? JYPinyinHelper.toHanyuPinyin(city) : city.toLowerCase();
            }
        }


        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
//        if (ValidateUtil.isNull(city)) {
//            return AjaxResult.errorResult("市不能为空");
//        }

        //检测用户是否已经存在
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {//系统中无该用户
            //新建公司账号
            UserInfo u = new UserInfo(UserType.COMPANY, username, name, signature, telPhone, phone2, sex,
                    province, city, county, address, user.getUsername());
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
                    psw = username.substring(5, 11);
                }
                ResultInfo resultInfo = User.addUser(u, psw);
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } catch (Exception e) {
                return AjaxResult.errorResult("新增失败，请稍后再试");
            }

        } else {
            return AjaxResult.errorResult("当前用户已存在");
        }

        return AjaxResult.successResult();
    }

    // 公司账号下拉
    @RequestMapping(method = RequestMethod.POST, value = "/user/company/select")
    @ResponseBody
    public String user_select(String token, Integer userType, Long startTime, Long endTime) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotAbsInteger(userType)) {
            userType = 5;
        }
        List<UserInfoVO> list = getUserList(userType, false, startTime, endTime);  // 获取所有用户List<Object> re = null;
        List<Object> re = null;
        if (ValidateUtil.isAbsList(list)) {
            re = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> data = new HashMap<>();
                data.put("username", list.get(i).getUsername());
                data.put("name", list.get(i).getName());
                re.add(data);
            }
        }


        return AjaxResult.successResult(re.size(), re);
    }


    //-------------------------------------------
    //分类获取用户
//    private List<UserInfoVO> getUserList(int userType) {
//        List<UserInfo> list = UserInfoMemory.getInstance().list(userType);
//        if (null == list) {
//            return null;
//        }
//
//        List<UserInfoVO> voList = new ArrayList<UserInfoVO>();
//        for (int i = 0; i < list.size(); i++) {
//            if (null == list.get(i)) {
//                continue;
//            }
//
//            UserInfoVO userInfoVO = new UserInfoVO();
//            try {
//                ObjectUtils.copyPropertiesExclude(list.get(i), userInfoVO, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//                continue;
//            }
//            if (null == userInfoVO) {
//                continue;
//            }
//            if (ValidateUtil.isNotNull(userInfoVO.getSignPhoto()) && ValidateUtil.isNotNetUrl(userInfoVO.getSignPhoto())) {
//                userInfoVO.setSignPhoto(Common.imageUrl + userInfoVO.getSignPhoto());
//            }
//            voList.add(userInfoVO);
//        }
//
//        return voList;
//    }

    //分类获取已锁定用户
    private List<UserInfoVO> getUserList(int userType, boolean isLock) {
        return getUserList(userType, isLock, null, null);
    }

//    private List<UserInfoVO> getUserList(boolean isLock, Long startTime, Long endTime) {
//        return getUserList(0, isLock, startTime, endTime);
//    }

    private List<UserInfoVO> getUserList(int userType, boolean isLock, Long startTime, Long endTime) {
        List<UserInfo> list = null;
        if (userType - UserType.ALL == 0) {
            list = UserInfoMemory.getInstance().listV2(); // 获取所有用户
        } else {
            list = UserInfoMemory.getInstance().list(userType);  // 按类型获取
        }

        if (null == list) {
            return null;
        }

        List<UserInfoVO> voList = new ArrayList<UserInfoVO>();
        for (int i = 0; i < list.size(); i++) {
            if (null == list.get(i)) {
                continue;
            }

            if (isLock && !User.isLocked(list.get(i).getIsLock())) {
                continue;
            }

            if (null != startTime) {
                if (list.get(i).getCreateTime() - startTime < 0) {
                    continue;
                }
            }
            if (null != endTime) {
                if (list.get(i).getCreateTime() - endTime > 0) {
                    continue;
                }
            }

            UserInfoVO userInfoVO = new UserInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(list.get(i), userInfoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null == userInfoVO) {
                continue;
            }
            if (ValidateUtil.isNotNull(userInfoVO.getSignPhoto()) && ValidateUtil.isNotNetUrl(userInfoVO.getSignPhoto())) {
//                userInfoVO.setSignPhoto(Common.imageUrl + userInfoVO.getSignPhoto());
                userInfoVO.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + userInfoVO.getSignPhoto());
            }
            // 授予角色
            UserRoleUtils.analysisUserRoles(userInfoVO);
            // 将用户的你登录账号代替用户的额唯一标识
//            if (SYS_SETTINGS.LOGIN_TYPE_BY != null && SYS_SETTINGS.LOGIN_TYPE_BY == 1 && ValidateUtil.isNotNull(userInfoVO.getPhone())) {
//                userInfoVO.setUsername(userInfoVO.getPhone());
//            }
            voList.add(userInfoVO);
        }

        return voList;
    }

    // 获取今日用户量
    public Long getTodayUserCount(List<UserInfoVO> list, Long startTime, Long endTime) {
        long count = 0;
        for (int i = 0; i < list.size(); i++) {
            UserInfoVO userInfo = list.get(i);
            if (null == userInfo) {
                continue;
            }
            if (startTime < userInfo.getCreateTime() && userInfo.getCreateTime() < endTime) {
                count++;
            }
        }

        return count;
    }


    //锁定或解锁用户
    public static ResultInfo lockUser(String updateUser, String usernames, int isLock) {
        String usStr = usernames.replaceAll(",", "','");
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.UserInfo).append(" set isLock = ").append(isLock).append(",updateUser = '")
                .append(updateUser).append("' where username in ('").append(usStr).append("') and delFlag = 0");

        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("锁定用户失败，请稍后再试");
        }
        UserInfoMemory.getInstance().lock(usernames);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_LOCK).setStr01(usernames);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 将用户token剔除
        Set<String> splitToSet = CommonUtils.splitToSet(usernames, String.class);
        if (splitToSet != null && !splitToSet.isEmpty()) {
            splitToSet.forEach(item -> {
                MemcacheUtil.removeByUsername(item); // 删除token
            });
        }
        return new ResultInfo();
    }


    // 设置或取消为分销商（角色）
    @RequestMapping("/admin/user/grant-cancel/user-role")
    @ResponseBody
    public String grantUserRole(String token, String username, @RequestParam(defaultValue = "grant") String operating, @RequestParam(defaultValue = "2") Integer userRole) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        // Integer code = SysSettingMobileMemory.getInstance().getValueByCode(SysSettingMobileConstant.DISTRIBUTION_MODEL);
        Integer code = SYS_SETTINGS.DISTRIBUTION_MODEL;
        if (code != 1) {
            return AjaxResult.errorResult("当前非部分分销模式");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (userInfo == null) {
            return AjaxResult.errorResult("未获取到用户信息,请核实");
        }
        if (!UserRoleUtils.isSysUserRole(userRole)) {
            return AjaxResult.errorResult("未知的用户角色");
        }
        Integer userRole_db = userInfo.getUserRole();
        if ("grant".equals(operating)) {
            userRole_db = UserRoleUtils.grantUserRole(userRole_db, userRole);
        } else if ("cancel".equals(operating)) {
            userRole_db = UserRoleUtils.cancelUserRole(userRole_db, userRole);
        } else {
            return AjaxResult.errorResult("未知的操作类型");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.UserInfo).append(" set updateUser ='")
                .append(user.getUsername()).append("', userRole = ").append(userRole_db)
                .append(" where username ='").append(username).append("' and delFlag = 0");
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection();
            con.setAutoCommit(false);
            if (userRole == UserRoleUtils.user_role_distribution) {
                this.updateRemoteDistribute(username, operating);
            }
            UserDaoSql.getInstance().executeBySql(sql.toString(), con);
            con.commit();
        } catch (Exception e) {
            UserDaoSql.getInstance().rollback(con);
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        // cache
        UserInfoMemory.getInstance().modifyUserInfo(username);
        return AjaxResult.successResult();
    }

    // 远程关闭某用户的分销功能
    public void updateRemoteDistribute(String username, String operating) throws Exception {
        // 全民分销
        // Integer code = SysSettingMobileMemory.getInstance().getValueByCode(SysSettingMobileConstant.DISTRIBUTION_MODEL);
        Integer code = SYS_SETTINGS.DISTRIBUTION_MODEL;
        if (code - 1 == 0) { // 部分分销
            Integer distributeState = 1;
            if (!operating.equals("grant")) {
                distributeState = 2;
            }
            String requestStr = HttpRequest.sendPost(SYS_CONFIG_PATH.FEN_XIAO_SERVICE_URL + "/api/distribute/user/relation/distribute-state/update"
                    , "username=" + username + "&distributeState=" + distributeState + "&sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY);
            DeviceCompanyContact companyContact = new Gson().fromJson(requestStr, DeviceCompanyContact.class);
            if (null == companyContact || 0 == companyContact.getStatus()) {
                throw new Exception("分销人员修改失败");
            }
            if (0 == 1 - companyContact.getStatus()) {
                System.out.println("分销人员修改成功 " + username);
            }
        }
    }

    //单独图片上传
    @RequestMapping(method = RequestMethod.POST, value = "/user/image/upload")
    @ResponseBody
    public String user_add(String token, FileUploadInfo fileUploadInfo, Integer fileType) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == fileUploadInfo) {
            return AjaxResult.errorResult("图片不允许为空");
        }

        if (null == fileUploadInfo.getImage() && ValidateUtil.isNull(fileUploadInfo.getBase64Img())) {
            return AjaxResult.errorResult("图片不允许为空.");
        }
        String filePath = null;

        String folder = SYS_CONFIG_PATH.USER_IMAGE;
        //照片
//        if (null != fileUploadInfo.getImage()) {
//            //存储图片
////            filePath = JYImageUtils.saveImage(Common.SHOPIMAGE, fileUploadInfo.getImage());
//            filePath = JYImageUtils.saveImage(folder, fileUploadInfo.getImage());
//            if (ValidateUtil.isNull(filePath)) {
//                return AjaxResult.errorResult("存储图片失败，请稍后再试");
//            }
//        }
        if (fileUploadInfo.getImage() != null || StringUtils.isNotEmpty(fileUploadInfo.getBase64Img())) {
            filePath = StringUtils.isNotEmpty(fileUploadInfo.getBase64Img()) ? JYImageUtils.saveImage(folder, fileUploadInfo.getBase64Img()) : JYImageUtils.saveImage(folder, fileUploadInfo.getImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存图片失败");
            }
        }

        HashMap<String, String> map = new HashMap<String, String>();
        if (ValidateUtil.isNetUrl(filePath)) {
            map.put("imageUrl", filePath);
        } else {
            map.put("imageUrl", SYS_CONFIG_PATH.IMAGE_BASE_URL + filePath);
        }
        map.put("imagePath", filePath);

        return AjaxResult.successResult(map);

    }

    // 获取待审核的用户企业列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/company/verify/list")
    @ResponseBody
    public String user_company_verify_list(String token, String username, String states, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 1;
        }
        Set<Integer> stateSet = new HashSet<>();
        if (ValidateUtil.isNotNull(states)) {
            stateSet = CommonUtils.splitToSet(states, Integer.class);
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" from ").append(PojoTables.UserInfo)
                .append(" where delFlag = 0 ");
        if (ValidateUtil.isNotNull(username)) {
            sql.append(" and username  like '").append(username).append("' ");
        }
        if (stateSet.size() > 0) {
            sql.append(" and companyUserState in (").append(StringUtils.join(stateSet, ",")).append(") ");
        }
        String listSql = " select * " + sql.toString() + " order by id desc limit " + (page - 1) * size + "," + size;
        String countSql = " select count(1) as counts " + sql.toString();
        long count = 0;
        List<UserInfo> list = null;
        try {
            count = UserDaoSql.getInstance().getCount(countSql);
            list = (List<UserInfo>) UserDaoSql.getInstance().list(UserInfo.class, listSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (ValidateUtil.isAbsList(list)) {
            List<UserInfoVO> reList = new ArrayList<>();
            for (UserInfo userInfo : list) {
                UserInfoVO vo = new UserInfoVO();
                BeanUtils.copyProperties(userInfo, vo);
                if (ValidateUtil.isNotNull(vo.getSignPhoto()) && ValidateUtil.isNotNetUrl(vo.getSignPhoto())) {
                    vo.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getSignPhoto());
                }
                UserInfoExtra userInfoExtra = UserInfoExtraMemory.getInstance().getByUsername(userInfo.getUsername());
                if (userInfoExtra != null) {
                    vo.setUserInfoExtra(userInfoExtra);
                }
                reList.add(vo);
            }
            return AjaxResult.successResult(reList, count);
        }
        return AjaxResult.successResult(null, 0);
    }


    // 审核企业用户
    @RequestMapping(method = RequestMethod.POST, value = "/user/company/state/verify")
    @ResponseBody
    public String user_company_state_verify(String token, String username, Integer state) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (userInfo == null) {
            return AjaxResult.errorResult("未获取到信息");
        }
        if (Optional.ofNullable(userInfo.getCompanyUserState()).orElse(0) - USER_COMPANY_STATE.STATE_COMPANY_VERIFY != 0) {
            return AjaxResult.errorResult("用户未发起审核");
        }
        if (state == null) {
            state = USER_COMPANY_STATE.STATE_COMPANY_PASS;
        }
        StringBuffer slq = new StringBuffer();
        slq.append(" update ").append(PojoTables.UserInfo).append(" set companyUserState= ").append(state)
                .append(" where delFlag = 0  and username ='").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(slq.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        UserInfoMemory.getInstance().modifyUserInfo(username);
        return AjaxResult.successResult();
    }

    public static void main(String[] args) {

        //        String usernames = "18660176355,15553119335,15666371607";
//        String[] Arr = usernames.split(",");
//        List<UserInfo> list = new ArrayList<>();
//        if (null != Arr) {
//            for (int i = 0; i < Arr.length; i++) {
//                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(Arr[i]);
//
//                if (userInfo != null) {
//                    list.add(userInfo);
//                }
//            }
//        }

    }

}
